import { roomInfo} from "../room/room.js";

import commonConstant from "../common/commonConstant.js";
import {userInfo} from "../user.js";
import {delObjInArr} from "../util/arrayUtil.js";
import {canvasUtil} from "../util/canvasUtil";
import {globalData} from "../globalData/globalData";
import {themeColor} from "../common/themeColor";
import {imageCollection} from "../globalData/imageCollection";
import {getTouchTarget, isOnElement, isOnElements} from "../util/touchUtil";
import {clearElements, elements} from "../globalData/elements";
import {chessConfig} from "./chessConfig";
import {gameData, localGameData, elementType, canMoveAreaArr, canBuildAreaArr, computeSize} from "./gameData";
import {ws} from "../../adaptor/netConfig";


export class Game{
    constructor() {
        globalData.canvas.addEventListener('touchstart', touchHandlerGaming)
        // initGameData()
        computeSize(globalData.screenWidth)
        gameData.startY=100

    }
}


const getX = (i) => {
    // console.log(chess);
    return (i - 1) * gameData.chessWidth
}
const getY = (j) => {
    return (j - 1) * gameData.chessHeight + gameData.startY
}

const getCenterX = (i) => {
    // console.log(chess);
    let x = getX(i)
    return  x+ gameData.chessWidth/2
}
const getCenterY = (j) => {
    // console.log(chess);
    let y =  getY(j)
    return y+ gameData.chessHeight/2
}

const getIByX = (x) => {
    return Math.floor(x/gameData.chessWidth +1)
}
const getJByY = (y) => {
    return Math.floor((y-gameData.startY)/gameData.chessHeight +1)
}

export const updateGameData = (_gameData) => {
    Object.assign(gameData, _gameData)
}

const sendGameData = () => {
    console.log('synchronizedGameData', gameData);
    // ws.send(JSON.stringify({
    //     cmd: commonConstant.CMD_UPDATE_GAME_DATA,
    //     roomNumber: roomInfo.number,
    //     data: gameData
    // }))

    ws.sendMsg({
        cmd: commonConstant.CMD_UPDATE_GAME_DATA,
        roomNumber: roomInfo.number,
        data: gameData
    })
    // wx.sendSocketMessage({
    //     data:JSON.stringify({
    //         cmd: commonConstant.CMD_UPDATE_GAME_DATA,
    //         roomNumber: roomInfo.number,
    //         data: gameData
    //     })
    // })
}

const sendTurnChange = () => {
    console.log('synchronizedGameData', gameData);
    // ws.send(JSON.stringify({
    //     cmd: commonConstant.CMD_UPDATE_GAME_DATA,
    //     roomNumber: roomInfo.number,
    //     data: gameData
    // }))

    ws.sendMsg({
        cmd: commonConstant.CMD_GAME_TURN_CHANGE,
        roomNumber: roomInfo.number,
        data: gameData.turn
    })
    // wx.sendSocketMessage({
    //     data:JSON.stringify({
    //         cmd: commonConstant.CMD_GAME_TURN_CHANGE,
    //         roomNumber: roomInfo.number,
    //         data: gameData.turn
    //     })
    // })
}


export const startGame = (map) => {

    // initGameData()


    // gameData.minaArea.push(...map.minaArea)
    // gameData.mountainArea.push(...map.mountainArea)
    // gameData.wallArea.push(...map.wallArea)
    // gameData.waterArea.push(...map.waterArea)
    gameData.turn=userInfo.id
    initUnExploreArea()
    updateVisibleArea()
    gameData.player1.id = userInfo.id
    gameData.player1.name = userInfo.name
    gameData.status=commonConstant.GAME_STATUS_PLAYING

    ws.sendMsg({
        cmd: commonConstant.CMD_START_GAME,
        roomNumber: roomInfo.number,
        data: gameData
    })
    // wx.sendSocketMessage({
    //     data: JSON.stringify({
    //         cmd: commonConstant.CMD_START_GAME,
    //         roomNumber: roomInfo.number,
    //         data: gameData
    //     })
    // })



    renderGame()


}
const initUnExploreArea = () => {
    for (let i = 1; i <= gameData.col; i++) {
        for (let j = 1; j <= gameData.row; j++) {
            gameData.player1.unexploredArea.push([i,j])
            gameData.player2.unexploredArea.push([i,j])
        }
    }
}

export const onWSStartGame = (data) => {

    // initGameData()
    updateGameData(data)
    gameData.player2.id = userInfo.id
    gameData.player2.name = userInfo.name
    // selfId = gameData.player2.id
    updateVisibleArea()
    sendGameData()



    renderGame()

    // canvas.addEventListener('touchstart', touchHandlerGaming)

}

export const onWSGameDataUpdate = (data) => {
    updateGameData(data)
    // updateVisibleArea()
    // Object.assign(animationInfo,data.animationInfo)
    initAnimationInfo(gameData.animationInfo.chess,gameData.animationInfo.startI,gameData.animationInfo.startJ,gameData.animationInfo.toI,gameData.animationInfo.toJ)
    doAnimateInterval()
    if(gameData.animationInfo.chess){
        setTimeout(renderGame,gameData.animationInfo.duration)
    }else {
        renderGame()
    }

}

export const onWSAnimationInfo = (data) => {
    Object.assign(gameData.animationInfo,data)
    doAnimateInterval()
}

export const  onWSTurnChange = (turn) => {
    isTurnChanged = true
    renderGame()
    setTimeout(() => {
        isTurnChanged=false
        renderGame()
    },500)
}
let selectedChess, selectBuildChess
export const onAreaClick = (i, j) => {

    console.log('onAreaClick', i, j)
    if(gameData.status===commonConstant.GAME_STATUS_OVER)  return;
    if(gameData.turn!==getPlayer().id) return;
    if(!selectedChess && !selectBuildChess) return

    if (selectedChess) {
        if(!canMove(selectedChess,i,j)) return;
        // updateMoney()
        clearCanMoveArea()
        clearCanBuildArea()
        initAnimationInfo(selectedChess, selectedChess.i, selectedChess.j,i,j)
        selectedChess.i = i
        selectedChess.j = j
        selectedChess.moved=true
        delObjInArr(gameData.wallArea,[i,j])


    } else if (selectBuildChess) {
        //选定位置不能建造
        if(!canBuild(i,j)) return;
        //减去花费
        let b = costMoney(selectBuildChess.cost)
        if(!b) return;
        // updateMoney()
        let player = getPlayer()
        player.chessArr.push({
            name: selectBuildChess.name,
            i: i,
            j: j,
            exp:0,
            isElite: false,
            moved: true,
            sellPrice:chessConfig[selectBuildChess.name].sellPrice
        })
        //建造完后,开始冷却,+1是因为,等会更新冷却时间时,会多减一次冷却
        //每三个象/相 可以减一回合冷却
        let xiangCount=countXiang()
        let n = Math.floor(xiangCount/3)
        selectBuildChess.cooling=selectBuildChess.coolTotal+1-n
        // 最少有1回合冷却
        if(selectBuildChess.cooling<1) selectBuildChess.cooling = 1
        selectBuildChess = null
        // endThisTurn()
    }

    //结束回合
    // setTimeout(() => {
    //     endThisTurn()
    // },animationInfo.duration)
    endThisStep()



}

const costMoney = (cost) => {
    let  player = getPlayer()
    if(player.money.total<cost){
        return false
    }
    player.money.total-=cost
    return true
}

const updateMoney = () => {
    let  player = getPlayer()
    //查找有多少个士位于金矿山,加钱
    let shiOnMina=0
    let shiOnMina_elite=0
    for (let chess of player.chessArr) {
        if(chess.name==='士' || chess.name==='仕' ){
            if(isMinaArea(chess.i,chess.j)){
                if(chess.isElite){
                    shiOnMina_elite++
                }else {
                    shiOnMina++
                }

            }
        }
    }
    player.money.increase=shiOnMina*chessConfig['士'].moneyEachTurn+shiOnMina_elite*shiOnMina*chessConfig['士_精英'].moneyEachTurn
    player.money.total+=player.money.increase
    return true
}

export const onChessClick = (chess) => {
    console.log('onChessClick', chess)
    if(gameData.status===commonConstant.GAME_STATUS_OVER)  return;
    if(gameData.turn!==getPlayer().id) return;
    if(selectedChess){
        //已经选中棋子了,然后选中了敌方棋子,判读能否吃子;如果选中己方棋子,更新选中
        selectBuildChess = null
        if(hasSelfChess(chess.i,chess.j)){
            selectedChess = chess
            clearCanBuildArea()
            updateCanMoveArea(chess)
            renderGame()
        }else if(hasEnemyChess(chess.i,chess.j)){
            let b =canMove(selectedChess,chess.i,chess.j)
            if(b){
                //可以吃子
                clearCanMoveArea()
                clearCanBuildArea()
                initAnimationInfo(selectedChess,selectedChess.i, selectedChess.j,chess.i,chess.j)
                //移除敌方棋子
                delObjInArr(getEnemy().chessArr,chess)
                if((selectedChess.name==='红炮'||selectedChess.name==='黑炮') && selectedChess.isElite){
                    //精英炮,打一圈
                    for(let _i = chess.i-1;_i<=chess.i+1;_i++){
                        for(let _j = chess.j-1;_j<=chess.j+1;_j++){
                            let _chess = getChess(_i,_j)
                            if(_chess){

                                //移除敌方棋子
                                delObjInArr(getEnemy().chessArr,_chess)
                                console.log('精英炮',_chess,JSON.stringify(getEnemy().chessArr));
                                //移除己方棋子
                                delObjInArr(getPlayer().chessArr,_chess)
                            }
                        }
                    }
                }

                //更新棋子经验
                let _exp = chessConfig[chess.name].exp
                if(chess.isElite){
                    _exp = chessConfig[chess.name+'_精英'].exp
                }
                selectedChess.exp+=_exp
                if(selectedChess.exp>=chessConfig[selectedChess.name].eliteNeedExp){
                    selectedChess.isElite=true
                }

                //更新棋子位置
                selectedChess.i = chess.i
                selectedChess.j = chess.j
                selectedChess.moved=true
                if(isGameOver()){
                    gameData.status=commonConstant.GAME_STATUS_OVER
                }

                //结束回合
                endThisStep()

            }
        }
    }else if(isSelfChess(chess) && !chess.moved){
        selectedChess = chess
        clearCanBuildArea()
        updateCanMoveArea(chess)
        renderGame()
    }


}

const endThisStep = () => {
    doAnimateInterval()
    selectedChess = null
    selectBuildChess = null
    // gameData.turn = getEnemy().id
    updateCanBuildChessArr()
    updateVisibleArea()
    // updateCooling()
    sendGameData()
    clearCanMoveArea()
    clearCanBuildArea()
    isGameOver()

    if(gameData.animationInfo.chess){
        setTimeout(renderGame,gameData.animationInfo.duration)
    }else {
        renderGame()
    }
}

const endThisTurn = () => {
    gameData.turn = getEnemy().id
    //结束回合后重置棋子的可移动
    for (let chess of getPlayer().chessArr) {
        chess.moved=false
    }
    updateMoney()
    updateCooling()
    sendGameData()
    clearCanMoveArea()
    clearCanBuildArea()
    sendTurnChange()
    onWSTurnChange()
    renderGame()
}


export const onCanBuildChessClick = (chess) => {
    console.log('onCanBuildChessClick', chess)
    if(gameData.status===commonConstant.GAME_STATUS_OVER)  return;
    if(gameData.turn!==getPlayer().id) return;
    // selectedChess = chess
    //没有冷却完,不能点
    if(chess.cooling>0) return;
    //钱不够,不能建造
    if(chess.cost>getPlayer().money.total) return;
    selectedChess = null
    selectBuildChess = chess
    clearCanMoveArea()
    updateCanBuildArea()
    renderGame()
}

const touchHandlerGaming = (e) => {
    e.preventDefault()
    console.log('touchHandlerGaming');
    const x = e.touches[0].clientX
    const y = e.touches[0].clientY

    let idArr = getTouchTarget(x,y)
    if(idArr.length===0) return;

    if(idArr.length===1 && idArr[0]==='info'){
        //点击了再来一局
        startGame()
        return;
    }

    if(idArr.length===1 && idArr[0]==='endTurn'){
        //点击了结束回合
        endThisTurn()
        return;
    }

    if(idArr.length===1 && idArr[0]==='sell'){
        //点击了售卖
        sell(selectedChess)
        return;
    }

    let id = getIdByType(idArr,elementType.shadow)
    if(id) return;
    let type
    id = getIdByType(idArr,elementType.chess)
    type = elementType.chess

    if(!id){
        id=getIdByType(idArr,elementType.canBuildChess)
        type = elementType.canBuildChess
    }

    if(!id){
        id=getIdByType(idArr,elementType.area)
        type = elementType.area
    }

    if(!id) return;

    let ids = id.split('_')
    if(ids.length<3) return
    let i=ids[1],j=ids[2]

    if(type=== elementType.chess){
        let chess = getChess(parseInt(i),parseInt(j))
        if(!chess) return;
        onChessClick(chess)
    }else if(type === elementType.area){
        onAreaClick(parseInt(i),parseInt(j))
    }else if(type === elementType.canBuildChess){
        //对于 canbuildchess,i 是 chessName, j是cost
        let chess = getCanBuildChess(ids[1])
        onCanBuildChessClick(chess)
    }
}

const isMinaArea = (i,j) => {
    return gameData.minaArea.some(area=>area[0]===i&&area[1]===j)
}

let turnInterval,turnNumber,isTurnChanged

export const renderChessDirectly=()=>{
    for (let chess of gameData.player1.chessArr) {
        canvasUtil.drawImg(getX(chess.i),getY(chess.j),gameData.chessWidth,gameData.chessHeight,imageCollection[chess.name])
    }
    for (let chess of gameData.player2.chessArr) {
        canvasUtil.drawImg(getX(chess.i),getY(chess.j),gameData.chessWidth,gameData.chessHeight,imageCollection[chess.name])
    }
}

export const renderMap = () => {
    //渲染棋盘
    // canvasUtil.drawImg(0,0,globalData.screenWidth,globalData.screenHeight,imageCollection['chessboard'])
    for (let i = 1; i <= gameData.col; i++) {
        let x = getX(i)
        canvasUtil.drawLine(x+gameData.chessWidth/2,gameData.startY+gameData.chessHeight/2,x+gameData.chessWidth/2,gameData.startY+gameData.chessHeight/2+gameData.chessBoardHeight,2,themeColor.black)
    }
    for (let j = 1; j <= gameData.row; j++) {
        let y = getY(j)
        canvasUtil.drawLine(gameData.chessWidth/2,y+gameData.chessHeight/2,gameData.chessWidth/2+gameData.chessBoardWidth,y+gameData.chessHeight/2,2,themeColor.black)
    }
    // canvasUtil.drawRect('chessBoard','chess',0,startY,gameData.chessBoardWidth,gameData.chessBoardHeight,themeColor.bgColor2)

    for (let i = 1; i <= gameData.col; i++) {
        for (let j = 1; j <= gameData.row; j++) {
            let x = getX(i)
            let y = getY(j)
            let id = getAreaId(i, j)
            let rect
            canvasUtil.drawBaseArea(id,'',x,y,gameData.chessWidth,gameData.chessHeight)
        }
    }

    //渲染金矿
    for (let minaArea of gameData.minaArea) {
        let x = getX(minaArea[0])
        let y = getY(minaArea[1])
        // let id = getMinaAreaId(minaArea.i, minaArea.j)
        canvasUtil.drawRect(x,y,gameData.chessWidth,gameData.chessHeight,themeColor.gold)
    }
    //渲染山区
    for (let area of gameData.mountainArea) {
        let x = getX(area[0])
        let y = getY(area[1])
        // let id = getMinaAreaId(area.i, area.j)
        canvasUtil.drawImg(x,y,gameData.chessWidth,gameData.chessHeight,imageCollection['mountain'])
    }
    //渲染山区
    for (let area of gameData.wallArea) {
        let x = getX(area[0])
        let y = getY(area[1])
        // let id = getMinaAreaId(area.i, area.j)
        canvasUtil.drawImg(x,y,gameData.chessWidth,gameData.chessHeight,imageCollection['wall'])
    }
    //渲染山区
    for (let area of gameData.waterArea) {
        let x = getX(area[0])
        let y = getY(area[1])
        // let id = getMinaAreaId(area.i, area.j)
        canvasUtil.drawImg(x,y,gameData.chessWidth,gameData.chessHeight,imageCollection['water'])
    }
}
export const renderGame = () => {
    clearElements()
    canvasUtil.clearCanvas()
    console.log('渲染游戏');

    renderMap()



    //渲染棋子
    for (let chess of gameData.player1.chessArr) {
        renderChess(chess)
    }
    for (let chess of gameData.player2.chessArr) {
        renderChess(chess)
    }

    //渲染执行动画的棋子
    if(gameData.animationInfo.chess){
        let i = getIByX(gameData.animationInfo.startX)
        let j = getJByY(gameData.animationInfo.startY)
        if(visible(i,j)){
            canvasUtil.drawImg(gameData.animationInfo.startX,gameData.animationInfo.startY,gameData.chessWidth,gameData.chessHeight,imageCollection[gameData.animationInfo.chess.name])
        }
    }




    //渲染选中的棋子可以落子的Area
    for (let canMoveArea of canMoveAreaArr) {
        let x = getCenterX(canMoveArea.i)
        let y = getCenterY(canMoveArea.j)
        canvasUtil.drawCanMoveArea(x,y,gameData.chessWidth/5,themeColor.color2)
    }
    //渲染选中的可建造棋子可以建造的地方
    for (let canBuildArea of canBuildAreaArr) {
        let x = getX(canBuildArea.i)
        let y = getY(canBuildArea.j)
        canvasUtil.drawCanBuildArea(x,y,gameData.chessWidth,gameData.chessHeight)
    }

    //渲染战争迷雾
    let player = getPlayer()
    for (let i = 1; i <= gameData.col; i++) {
        for (let j = 1; j <= gameData.row; j++) {
            let x = getX(i)
            let y = getY(j)
            let id = getShadowId(i, j)
            if(!visible(i,j)){
                canvasUtil.drawMaskArea(id,'',x,y,gameData.chessWidth,gameData.chessHeight)
            }
        }
    }

    //渲染未探索区域
    for (let area of player.unexploredArea) {
        let x = getX(area[0])
        let y = getY(area[1])
        let id = getShadowId(area[0], area[1])
        canvasUtil.drawUnexploreArea(id,'',x,y,gameData.chessWidth,gameData.chessHeight)
    }




    //渲染建造栏
    for(let i=0;i<player.canBuildChessArr.length;i++){
        let canBuildChess = player.canBuildChessArr[i]
        if(!canBuildChess.show) continue
        let x = getX(i+1)
        let y = getY(gameData.row+1)


        let id = getCanBuildChessId(canBuildChess.name, canBuildChess.cost)

        canvasUtil.drawImgElement(id,canBuildChess.name,x,y,gameData.chessWidth,gameData.chessHeight,imageCollection[canBuildChess.name])
        canvasUtil.drawText(canBuildChess.cost,x+10,y+gameData.chessHeight+10,themeColor.green2)

        if(canBuildChess.cooling>0){
            canvasUtil.drawStrokeRectElement('','',x,y,gameData.chessWidth,gameData.chessHeight,themeColor.black2,themeColor.transparent)
            canvasUtil.drawText(canBuildChess.cooling,x+gameData.chessWidth/2-5,y+gameData.chessHeight/2+8,themeColor.color1,'30px bold')
        }else if(canBuildChess.cost > player.money.total){
            canvasUtil.drawStrokeRectElement('','',x,y,gameData.chessWidth,gameData.chessHeight,themeColor.black2,themeColor.transparent)
        }

    }

    //渲染选中的建造栏
    if(selectBuildChess){
        let id = getCanBuildChessId(selectBuildChess.name, selectBuildChess.cost)
        let ele  = elements.get(id)
        canvasUtil.drawStrokeRect(ele.x,ele.y,gameData.chessWidth,gameData.chessHeight,themeColor.transparent,themeColor.green2)
    }


    //
    let x = getX(8)
    let y = getY(gameData.row+1)
    canvasUtil.drawText(player.money.total,getX(1),50,themeColor.green2,'20')
    //渲染结束回合按钮
    if(gameData.turn === player.id){
        canvasUtil.drawRectElement('endTurn','结束回合',getX(8),y+10,80,30,themeColor.color2)
        canvasUtil.drawText('结束回合',getX(8),y+30,themeColor.green2,'20')
        canvasUtil.drawRectElement('sell','出售',getX(11),y+10,100,30,themeColor.red)
        canvasUtil.drawText('出售',getX(11),y+30,themeColor.green2,'20')
    }

    // 渲染回合
    let turn = gameData.turn===getPlayer().id?'己方回合':'对方回合'
    // let turn = ''
    if(gameData.status===commonConstant.GAME_STATUS_OVER){
        let winnerName = gameData.winner === gameData.player1.id?'红方赢':'黑方赢'
        let info = '游戏结束,'+winnerName+',再来一局!'
        canvasUtil.drawRectElement('info','info',0,getY(gameData.row+2)+30,150,20,themeColor.transparent)
        canvasUtil.drawText(info,20,getY(gameData.row+2)+40,themeColor.green2)
    }


    //画玩家1的name
    // canvasUtil.drawText(gameData.player1.name,getX(10),getY(gameData.row+2)+30,themeColor.green2)
    // //画玩家2的name
    // canvasUtil.drawText(gameData.player2.name,30,50,themeColor.green2)

    // if(turnInterval){
    //     clearInterval(turnInterval)
    // }
    // turnNumber = 1
    // renderTurn()
    // turnInterval = setInterval(renderTurn,500)

    if(isTurnChanged){
        renderTurnChange()
    }

}
const renderTurn = () => {
    let x = 15,y = 45,color=themeColor.black
    if(gameData.turn === gameData.player1.id){
        x = getX(9)+20
        y=getY(gameData.row+2)+25
    }
    // console.log('渲染turn',x,y,color);
    if(turnNumber%2===1) color=themeColor.green2

    canvasUtil.drawCircle(x,y,10,color)
    turnNumber=turnNumber%2+1
}

const renderTurnChange = () => {
    let turn = gameData.turn===getPlayer().id?'己方回合':'对方回合'
    canvasUtil.drawStrokeRect(getX(3),getY(9),gameData.chessWidth*7,gameData.chessHeight*3,themeColor.bgColor2,themeColor.gray)
    canvasUtil.drawText(turn,getX(5)+gameData.chessWidth/2,getY(10)+gameData.chessHeight/2,themeColor.green2,'50px')
}

const renderChess = (chess) => {
    let x = getX(chess.i)
    let y = getY(chess.j)
    let id = getChessId(chess.i, chess.j,chess.name)
    //执行动画的棋子不渲染,由后面单独渲染
    if(gameData.animationInfo.chess && gameData.animationInfo.chess.i===chess.i && gameData.animationInfo.chess.j===chess.j && gameData.animationInfo.chess.name===chess.name) return
    //不可见区域,不渲染棋子
    if(!visible(chess.i,chess.j)) return;
    canvasUtil.drawImgElement(id,chess.name,x,y,gameData.chessWidth,gameData.chessHeight,imageCollection[chess.name])
    if(chess.isElite){
        canvasUtil.drawImg(x+gameData.chessWidth/2,y+gameData.chessHeight/2,gameData.chessWidth/2.5,gameData.chessHeight/2.5,imageCollection['star'])
    }
    if(chess.moved){
        canvasUtil.drawCircle(getCenterX(chess.i),getCenterY(chess.j),gameData.chessWidth/2,themeColor.transparent2)
    }
    if(selectedChess && selectedChess.i===chess.i && selectedChess.j===chess.j && selectedChess.name === chess.name){
        //选中的棋子,渲染一个特效
        canvasUtil.drawStrokeRect(x,y,gameData.chessWidth,gameData.chessHeight,themeColor.transparent,themeColor.green2)
    }
}

const getRandomMinaArea = (number) => {
    let arr = []
    for(let k = 0;k<number;k++){
        let i=Math.ceil(Math.random()*gameData.col)
        let j=Math.ceil(Math.random()*gameData.row)
        arr.push({i,j})
    }
    return arr

}

const sell = (chess) => {
    if(!selectedChess) return
    getPlayer().money.total+=chess.sellPrice
    delObjInArr(getPlayer().chessArr,chess)
    endThisStep()
}
export const initGameData = () => {
    //生成随机矿点
    // let minaArea = getRandomMinaArea(5)
    // let minaArea = [{i:5,j:3},{i:5,j:17},{i:2,j:10},{i:6,j:10},{i:10,j:10}]




    // gameData = {
    //     //哪个玩家的回合
    //     turn: 0,
    //     //模式   1:选择棋子  2:选择移动目标
    //     // step: 1,
    //     //1:waiting  ; 2:playing ; 3:over
    //     status: commonConstant.GAME_STATUS_WAITING,
    //     winner:0,
    //     minaArea:[],
    //     mountainArea:[],
    //     wallArea:[],
    //     waterArea:[],
    //     animationInfo:animationInfo,
    //     player1: {
    //         id: 0,
    //         name:'',
    //         //'兵','红车','红马','红炮','相','仕','帅'
    //         canBuildChessArr: [
    //             {
    //                 name: '仕',
    //                 cost: 300,
    //                 show:true,
    //                 //冷却
    //                 cooling:0,
    //                 coolTotal:2,
    //             },
    //             {
    //                 name: '相',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:3,
    //             },
    //             {
    //                 name: '兵',
    //                 cost: 100,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:2,
    //             },
    //             {
    //                 name: '红车',
    //                 cost: 400,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //             {
    //                 name: '红马',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //             {
    //                 name: '红炮',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //
    //
    //             // {
    //             //     name: '帅',
    //             //     cost: '300',
    //             // }
    //         ],
    //         chessArr: [
    //             {
    //                 name: '帅',
    //                 i: 6,
    //                 j: 19,
    //                 isElite:false,
    //                 exp:0,
    //                 moved:false,
    //             },
    //             // {
    //             //     name: '红车',
    //             //     i: 8,
    //             //     j: 18,
    //             //     isElite:true,
    //             //     exp:1000,
    //             // },
    //
    //         ],
    //         unexploredArea:[],
    //         visibleArea: [],
    //         money: {
    //             total: 1000,
    //             increase: 0,
    //         }
    //     },
    //     player2: {
    //         id: 0,
    //         name:'',
    //         //'卒','黑车','黑马','黑炮','象','士','将'
    //         canBuildChessArr: [
    //             {
    //                 name: '士',
    //                 cost: 300,
    //                 show:true,
    //                 cooling:0,
    //                 coolTotal:2,
    //             },
    //             {
    //                 name: '象',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:3,
    //             },
    //             {
    //                 name: '卒',
    //                 cost: 100,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:2,
    //             },
    //             {
    //                 name: '黑车',
    //                 cost: 400,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //             {
    //                 name: '黑马',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //             {
    //                 name: '黑炮',
    //                 cost: 300,
    //                 show:false,
    //                 cooling:0,
    //                 coolTotal:5,
    //             },
    //
    //
    //             // {
    //             //     name: '将',
    //             //     cost: '300',
    //             // }
    //         ],
    //         chessArr: [
    //             {
    //                 name: '将',
    //                 i: 6,
    //                 j: 1,
    //                 isElite:false,
    //                 exp:0,
    //                 moved:false,
    //             },
    //
    //
    //         ],
    //         unexploredArea:[],
    //         visibleArea: [],
    //         money: {
    //             total: 1000,
    //             increase: 0,
    //         }
    //     },
    // }


}

export const updateVisibleArea = () => {
    console.log('updateVisibleArea');
    gameData.player1.visibleArea.length = 0
    let arr = getVisibleArea(gameData.player1.chessArr)
    gameData.player1.visibleArea.push(...arr)

    for (let area of arr) {
        delObjInArr(gameData.player1.unexploredArea,area)
    }

    gameData.player2.visibleArea.length = 0
    arr = getVisibleArea(gameData.player2.chessArr)
    gameData.player2.visibleArea.push(...arr)

    for (let area of arr) {
        delObjInArr(gameData.player2.unexploredArea,area)
    }

}
/**
 * 根据现有棋子,获取可见格子
 * @param chessArr
 */
export const getVisibleArea = (chessArr) => {
    let visibleArea = []
    for (let chess of chessArr) {
        let arr = []
        // let sight = sightObj[chess.name]
        let sight
        if(chess.isElite){
            sight = chessConfig[chess.name+'_精英'].sight
        }else {
            sight = chessConfig[chess.name].sight
        }

        arr = computeVisibleArea(chess.i, chess.j, sight)
        for (let area of arr) {
            if(!visibleArea.some(_area=>_area[0]===area[0] && _area[1]===area[1])){
                visibleArea.push(...arr)
            }
        }


    }

    return visibleArea
}

/**
 * 计算可见格子
 * @param i     棋子的i坐标
 * @param j     棋子的i坐标
 * @param distance   可视范围,格子数
 */
export const computeVisibleArea = (i, j, distance) => {
    let visibleAreaArr = []
    let startI = i - distance < 1 ? 1 : i - distance
    let endI = i + distance > gameData.col ? gameData.col : i + distance
    let startJ = j - distance < 1 ? 1 : j - distance
    let endJ = j + distance > gameData.row ? gameData.row : j + distance

    for (let _i = startI; _i <= endI; _i++) {
        for (let _j = startJ; _j <= endJ; _j++) {
            let d = Math.sqrt(Math.pow(_i-i,2)+Math.pow(_j-j,2))
            let _d = Math.round(d)
            //超出视野范围
            if(d>distance) continue
            if(!hasSightBlockArea(_i,_j,i,j)){
                visibleAreaArr.push([_i,_j])
            }

        }
    }

    return visibleAreaArr

}
/**
 * 计算起点与终点间是否存在障碍物,障碍物包括山,墙
 * 这个算法思路是,计算起始点的一元一次函数,
 * 然后计算可能经过的区域,
 * 然后计算可能经过的区域的四个角的坐标是否位于函数图像的同一侧,
 * 位于同一侧,则函数未穿过该区域,否则则穿过该区域.
 * 如果某个角位于函数图像上,也认为未穿过该区域
 * 如果穿过的区域是障碍物山,墙,则起点区域不可见
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 */
const hasSightBlockArea = (fromI,fromJ,toI,toJ) => {

    let x1 = getCenterX(fromI),y1=getCenterY(fromJ),x2=getCenterX(toI),y2=getCenterY(toJ)
    let k = (y2-y1)/(x2-x1)
    let b = y1-k*x1
    //y = kx+b


    let startI = fromI<=toI?fromI:toI
    let endI = fromI>toI?fromI:toI
    let startJ = fromJ<=toJ?fromJ:toJ
    let endJ = fromJ>toJ?fromJ:toJ

    for(let i = startI;i<=endI;i++){
        for(let j = startJ;j<=endJ;j++){
            if((i===fromI && j===fromJ) || (i===toI && j===toJ)){
                //起点和终点不用比较
                continue
            }

            //找出该区域的四个点坐标
            let _x1 = getX(i),_y1=getY(j),_x2=_x1+gameData.chessWidth,_y2=_y1,_x3=_x1,_y3=_y1+gameData.chessHeight,_x4=_x1+gameData.chessWidth,_y4=_y1+gameData.chessHeight
            let d1 = _y1 - (_x1*k+b)
            let d2 = _y2 - (_x2*k+b)
            let d3 = _y3 - (_x3*k+b)
            let d4 = _y4 - (_x4*k+b)
            let _d1 = Math.round(d1*100)/100
            let _d2 = Math.round(d2*100)/100
            let _d3 = Math.round(d3*100)/100
            let _d4 = Math.round(d4*100)/100

            if((_d1<=0&&_d2<=0&&_d3<=0&&_d4<=0) || (_d1>=0&&_d2>=0&&_d3>=0&&_d4>=0)){
                //未穿过该区域
            }else if(isMountain(i,j) || isWall(i,j)){
                //穿过该区域,并且该区域是山或者墙
                return true
            }
        }
    }

    return false
}
export const visible = (i, j) => {
    let player = getPlayer()
    return player && player.visibleArea.some(area => area[0] === i && area[1] === j);

}

const getPlayer = () => {
    let player = gameData.player1
    if (userInfo.id === gameData.player2.id) {
        player = gameData.player2
    }
    return player
}

const getEnemy = () => {
    let player = gameData.player1
    if (userInfo.id === gameData.player1.id) {
        player = gameData.player2
    }
    return player
}

//判断棋子能否移动
const canMove = (chess,toI,toJ) => {
    let b = false
    //首先排除自身和己方棋子
    if(chess.i===toI && chess.j===toJ) return b
    //本回合已经移动过了
    if(chess.moved) return false
    // b = isSelfChessByIJ(toI,toJ)

    if(hasSelfChess(toI,toJ) || isMountain(toI,toJ) || isWater(toI,toJ)){
        //如果目标是己方棋子,或者是山和水,则不能吃子
        return false
    }

    if(b) return false
    let invisibleCount = countInvisibleNumberOnline(chess.i,chess.j,toI,toJ)
    if(invisibleCount>0) return false
    let moveLength
    if(!chess.isElite){
        moveLength = chessConfig[chess.name].moveLength
    }else {
        moveLength = chessConfig[chess.name+'_精英'].moveLength
    }
    //相/象作为建筑,不能移动
    if (chess.name === '相' || chess.name === '象') return false

    if (chess.name === '将' || chess.name === '帅') {
        //横平竖直走1格
        if(toI===chess.i){
            if(Math.abs(toJ-chess.j)<=moveLength){
                b=true
            }
        }else if(toJ===chess.j){
            if(Math.abs(toI-chess.i)<=moveLength){
                b=true
            }
        }

        if(b){
            let roadBlockNumber = countRoadBlockNumberOnline(chess.i,chess.j,toI,toJ)
            if(roadBlockNumber===0  ){
                if( !hasRoadBlock(toI,toJ) ||hasEnemyChess(toI,toJ) || isWall(toI,toJ)){
                    //目标地点间没有障碍物或者目标是敌方棋子或者墙,可以移动
                    b=true
                }else {
                    //目标棋子是己方棋子
                    b=false
                }

            }else if(roadBlockNumber>0){
                //棋子与目标地点间有障碍物,不能移动
                b=false
            }

        }

    } else if (chess.name === '仕' || chess.name === '士') {
        //斜线走1格
        if(Math.abs(toI-chess.i)===moveLength && Math.abs(toJ-chess.j)===moveLength){
            b=true
        }
    } else if (chess.name === '相' || chess.name === '象') {
        //斜线走2格,不能堵象眼
        // if(Math.abs(toI-chess.i)===2 && Math.abs(toJ-chess.j)===2){
        //     if(!hasChess((toI+chess.i)/2,(toJ+chess.j)/2)){
        //         b=true
        //     }
        //
        // }
    }else if (chess.name === '红车' || chess.name === '黑车') {
        //横平竖直走4格
        if(toI===chess.i){
            if(Math.abs(toJ-chess.j)<=moveLength){
                b=true
            }
        }else if(toJ===chess.j){
            if(Math.abs(toI-chess.i)<=moveLength){
                b=true
            }
        }

        if(b){
            //先看该点是不是横平竖直的4格,如果是,再判断能不能走
            let roadBlockNumber = countRoadBlockNumberOnline(chess.i,chess.j,toI,toJ)
            if(roadBlockNumber===0  ){
                if( !hasRoadBlock(toI,toJ) ||hasEnemyChess(toI,toJ) || isWall(toI,toJ)){
                    //目标地点间没有障碍物或者目标是敌方棋子或者墙,可以移动
                    b=true
                }else {
                    //目标棋子是己方棋子
                    b=false
                }

            }else if(roadBlockNumber>0){
                //棋子与目标地点间有障碍物,不能移动
                b=false
            }

        }



    }else if (chess.name === '红马' || chess.name === '黑马') {

        let ti,tj
        //走日字,不能绊腿
        if((Math.abs(toI-chess.i)===1 && Math.abs(toJ-chess.j)===2)){
            ti=chess.i
            tj=(chess.j+toJ)/2
            if(!hasRoadBlock(ti,tj)){
                b=true
            }

        }else if(Math.abs(toI-chess.i)===2 && Math.abs(toJ-chess.j)===1){
            tj=chess.j
            ti=(chess.i+toI)/2
            if(!hasRoadBlock(ti,tj)){
                b=true
            }
        }
    } else if (chess.name === '红炮' || chess.name === '黑炮') {
        //翻山,有视野即可打过去,移动横平竖直走4格
        //横平竖直走4格
        if(toI===chess.i){
            if(Math.abs(toJ-chess.j)<=moveLength){
                b=true
            }
        }else if(toJ===chess.j){
            if(Math.abs(toI-chess.i)<=moveLength){
                b=true
            }
        }
        if((hasRoadBlockOnline(chess.i,chess.j,toI,toJ)) ){
            //如果路径上有障碍物,不能移动
            b=false
        }
        //如果不符合直走规则,判断是否符合翻山规则
        if(!b){
            if(countRoadBlockNumberOnline(chess.i,chess.j,toI,toJ)===1 && (hasEnemyChess(toI,toJ) || isWall(toI,toJ))){
                //翻山,且目标是敌方或者墙,可以开炮
                b=true
            }
        }
    }else if (chess.name === '兵' || chess.name === '卒') {
        //横平竖直走1格
        if(toI===chess.i){
            if(Math.abs(toJ-chess.j)<=moveLength){
                b=true
            }
        }else if(toJ===chess.j){
            if(Math.abs(toI-chess.i)<=moveLength){
                b=true
            }
        }
    }
    return b
}

/**
 * 移动规则1,横平竖直走
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 * @param dis       最远走动距离
 */
// const moveRule1 = (fromI,fromJ,toI,toJ,dis) => {
//     if(toI===fromI){
//         if(Math.abs(toJ-fromJ)<=dis){
//             return true
//         }
//     }else if(toJ===fromJ){
//         if(Math.abs(toI-fromI)<=dis){
//             return true
//         }
//     }
//
//     return false
// }


const hasChessOnLine = (fromI,fromJ,toI,toJ) => {
    return  hasSelfChessOnLine(fromI,fromJ,toI,toJ) || hasEnemyChessOnLine(fromI,fromJ,toI,toJ)
}

/**
 * 判断起点与终点之间有没有己方棋子,不包含起点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 */
const hasSelfChessOnLine = (fromI,fromJ,toI,toJ) => {
    let b = false
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start;j<=obj.end;j++){
            if(j===fromJ)continue
            b =  hasSelfChess(fromI,j)
            if(b) return b
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start;i<=obj.end;i++){
            if(i===fromI)continue
            b =  hasSelfChess(i,fromJ)
            if(b) return b
        }
    }

    return b
}

/**
 * 判断起点与终点之间有没有障碍物,不包含起点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 */
const hasRoadBlockOnline = (fromI,fromJ,toI,toJ) => {
    let b = false
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start;j<=obj.end;j++){
            if(j===fromJ)continue
            b =  hasRoadBlock(fromI,j)
            if(b) return b
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start;i<=obj.end;i++){
            if(i===fromI)continue
            b =  hasRoadBlock(i,fromJ)
            if(b) return b
        }
    }

    return b
}

const getStartAndEnd = (from,to) => {
    let res={}
    res.start= from>to?to:from
    res.end= from>to?from:to

    return res
}


/**
 * 判断起点与终点之间有没有敌方棋子,不包含起点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 */
const hasEnemyChessOnLine = (fromI,fromJ,toI,toJ) => {
    let b = false
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start;j<=obj.end;j++){
            if(j===fromJ)continue
            b =  hasEnemyChess(fromI,j)
            if(b) return b
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start;i<=obj.end;i++){
            if(i===fromI)continue
            b =  hasEnemyChess(i,fromJ)
            if(b) return b
        }
    }

    return b
}

/**
 * 计算起点和终点间有多少棋子,不包含起点与终点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 * @returns {number}
 */
const countChessNumberOnline = (fromI,fromJ,toI,toJ) => {
    let count = 0
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start+1;j<obj.end;j++){
            if(j===fromJ)continue
            if( hasChess(fromI,j)){
                count++
            }
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start+1;i<obj.end;i++){
            if(i===fromI)continue
            if( hasChess(i,fromJ)){
                count++
            }
        }
    }

    return count
}

/**
 * 计算起点和终点间有多少障碍物,障碍物包含棋子,山,墙,水,不包含起点与终点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 * @returns {number}
 */
const countRoadBlockNumberOnline = (fromI,fromJ,toI,toJ) => {
    let count = 0
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start+1;j<obj.end;j++){
            if(j===fromJ)continue
            if( hasRoadBlock(fromI,j)){
                count++
            }
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start+1;i<obj.end;i++){
            if(i===fromI)continue
            if( hasRoadBlock(i,fromJ)){
                count++
            }
        }
    }

    return count
}

/**
 * 计算起点和终点间有多少个不可见的区域,不包含起点与终点
 * @param fromI
 * @param fromJ
 * @param toI
 * @param toJ
 * @returns {number}
 */
const countInvisibleNumberOnline = (fromI,fromJ,toI,toJ) => {
    let count = 0
    if(fromI===toI){
        let obj = getStartAndEnd(fromJ,toJ)
        for(let j=obj.start+1;j<obj.end;j++){
            if(j===fromJ)continue
            if( !visible(fromI,j)){
                count++
            }
        }
    }else if(fromJ===toJ){
        let obj = getStartAndEnd(fromI,toI)
        for(let i=obj.start+1;i<obj.end;i++){
            if(i===fromI)continue
            if( !visible(i,fromJ)){
                count++
            }
        }
    }

    return count
}

/**
 * 判断指定坐标有没有棋子
 * @param i
 * @param j
 * @returns {boolean}
 */
const hasChess = (i,j) => {
    let b = gameData.player1.chessArr.some(chess=>chess.i===i&&chess.j===j)
    if(!b){
        b=  gameData.player2.chessArr.some(chess=>chess.i===i&&chess.j===j)
    }
    return b
}

const hasRoadBlock = (i,j) => {
    return hasChess(i,j)||isMountain(i,j)||isWall(i,j)||isWater(i,j)
}

const hasSelfChess = (i,j) => {
    return getPlayer().chessArr.some(chess=>chess.i===i&&chess.j===j)
}

const hasEnemyChess = (i,j) => {
    return getEnemy().chessArr.some(chess=>chess.i===i&&chess.j===j)
}

const isMountain = (i,j) => {
    return gameData.mountainArea.some(item=>item[0]===i&&item[1]===j)
}
const isWater = (i,j) => {
    return gameData.waterArea.some(item=>item[0]===i&&item[1]===j)
}
const isWall = (i,j) => {
    return gameData.wallArea.some(item=>item[0]===i&&item[1]===j)
}

/**
 * 获取可以建造的范围
 */
const canBuild = (i,j) => {
    //是不可见区域,不能建造
    if(!visible(i,j)) return  false
    //有棋子或者障碍物,不能建造
    let b =hasRoadBlock(i,j)
    if(b) return false
    for (let chess of getPlayer().chessArr) {
        let canBuildLength = chessConfig[chess.name].canBuildLength
        if(chess.isElite){
            canBuildLength = chessConfig[chess.name+'_精英'].canBuildLength
        }
        if(!canBuildLength) continue
        let d =  Math.round(Math.sqrt(Math.pow(i-chess.i,2)+Math.pow(j-chess.j,2)))
        if(d>canBuildLength){
            continue
        }

        let visibleArea = computeVisibleArea(chess.i,chess.j,canBuildLength)
        //看该点是否在视野范围内
        b = visibleArea.some(area=>area[0]===i&&area[1]===j)
        if(b){
            //有通路,返回true
            return b
        }

        // if(chess.name==='帅' || chess.name==='将' || chess.name==='相' || chess.name==='象' ){
        //
        // }
    }
    return false
}

//看图是否是联通的,即该点到chess是否有通路
const isLink = (i,j,chess) => {
}

/**
 * 判断游戏是否结束,当一方没有将或者帅时,游戏结束
 */
const isGameOver = () => {
    let shuaiCount=0,jiangCount=0
    for (let chess of gameData.player1.chessArr) {
        if(chess.name==='帅'){
            shuaiCount++
        }
    }



    for (let chess of gameData.player2.chessArr) {
        if(chess.name==='将'){
            jiangCount++
        }
    }

    if(shuaiCount>0 && jiangCount>0) return false
    if(shuaiCount===0){
        gameData.winner=gameData.player2.id
        return true
    }
    if(jiangCount===0){
        gameData.winner=gameData.player1.id
        return true
    }

}

const isSelfChess = (chess) => {

    return   getPlayer().chessArr.some(_chess=>_chess.i===chess.i&&_chess.j===chess.j&&_chess.name===chess.name)
}

//判断给定坐标是否是己方棋子
const isSelfChessByIJ = (i,j) => {

    return   getPlayer().chessArr.some(_chess=>_chess.i===i&&_chess.j===j)
}

/**
 * 判断己方是否有士
 */
const hasShi = () => {
    return   getPlayer().chessArr.some(_chess=>_chess.name==='士' || _chess.name==='仕')
}
/**
 * 判断己方是否有象
 */
const hasXiang = () => {
    return   getPlayer().chessArr.some(_chess=>_chess.name==='象' || _chess.name==='相')
}

const getChess = (i,j) => {
    let chessArr = gameData.player1.chessArr.filter(_chess=>_chess.i===i&&_chess.j===j)
    if(chessArr.length!==1){
        chessArr = gameData.player2.chessArr.filter(_chess=>_chess.i===i&&_chess.j===j)
    }

    if(chessArr.length===1) return chessArr[0]
    return null
}

export const getChessId = (i, j, chess) => {
    return `${elementType.chess}_${i}_${j}_${chess}`
}
export const getCanBuildChessId = ( chessName,cost) => {
    return `${elementType.canBuildChess}_${chessName}_${cost}`
}
export const getAreaId = (i, j) => {
    return `${elementType.area}_${i}_${j}`
}

export const getMinaAreaId = (i, j) => {
    return `${elementType.area}_${i}_${j}`
}

export const getShadowId = (i, j) => {
    return `${elementType.shadow}${i}_${j}`
}

/**
 * 根据类型,在id数组里找出以此类型字符串开头的id
 * @param arr
 * @param type
 * @returns {*|null}
 */
const getIdByType = (arr,type) => {
    let res = arr.filter(_item=>_item.startsWith(type))
    if(res.length!==1) return null
    return res[0]
}


const updateCanMoveArea = (chess) => {
    clearCanMoveArea()
    for (let i = 1; i <= gameData.col; i++) {
        for (let j = 1; j <= gameData.row; j++) {
            let b = canMove(chess,i,j)
            if(b){
                canMoveAreaArr.push({i,j})
            }
        }
    }

}
const clearCanMoveArea = () => {
    canMoveAreaArr.length=0
}

const updateCanBuildArea = () => {
    clearCanBuildArea()
    for (let i = 1; i <= gameData.col; i++) {
        for (let j = 1; j <= gameData.row; j++) {
            let b = canBuild(i,j)
            if(b){
                canBuildAreaArr.push({i,j})
            }
        }
    }

}

const clearCanBuildArea = () => {
    canBuildAreaArr.length=0
}

const updateCanBuildChessArr = () => {
    //有士才可以建造象
    //有象才可以建造车,马,炮,兵
    if(hasShi()){
        getPlayer().canBuildChessArr[1].show = true
    }else {
        getPlayer().canBuildChessArr[1].show = false
    }
    if(hasXiang()){
        getPlayer().canBuildChessArr[2].show = true
        getPlayer().canBuildChessArr[3].show = true
        getPlayer().canBuildChessArr[4].show = true
        getPlayer().canBuildChessArr[5].show = true
    }else {
        getPlayer().canBuildChessArr[2].show = false
        getPlayer().canBuildChessArr[3].show = false
        getPlayer().canBuildChessArr[4].show = false
        getPlayer().canBuildChessArr[5].show = false
    }

}


//更新可建造棋子的冷却
const updateCooling = () => {
    for (let canBuildChess of getPlayer().canBuildChessArr) {
        if(canBuildChess.cooling>0){
            canBuildChess.cooling--
        }
    }
}

const getCanBuildChess = (name) => {
    let chessArr = getPlayer().canBuildChessArr.filter(_item=>_item.name===name)
    if(chessArr.length===1) return chessArr[0]
    return null
}

const initAnimationInfo = (chess,startI,startJ,toI,toJ) => {
    gameData.animationInfo.chess = chess


    gameData.animationInfo.startI = startI
    gameData.animationInfo.startJ = startJ
    gameData.animationInfo.toI = toI
    gameData.animationInfo.toJ = toJ


    let startX = getX(startI)
    let startY = getY(startJ)
    let endX = getX(toI)
    let endY = getY(toJ)

    gameData.animationInfo.startX = startX
    gameData.animationInfo.startY = startY
    gameData.animationInfo.endX = endX
    gameData.animationInfo.endY = endY
    let totalX = endX - startX
    let totalY = endY-startY


    //每帧的间隔时间
    gameData.animationInfo.eachTime = Math.floor(gameData.animationInfo.duration/gameData.animationInfo.frame)
    let eachX = totalX/gameData.animationInfo.frame
    let eachY = totalY/gameData.animationInfo.frame

    gameData.animationInfo.eachX = eachX
    gameData.animationInfo.eachX_abs = Math.abs(eachX)
    gameData.animationInfo.eachY = eachY
    gameData.animationInfo.eachY_abs = Math.abs(eachY)

    // sendAnimationInfo()
    // doAnimateInterval()
}



let animationInterval
const doAnimateInterval = () => {
    if(gameData.animationInfo.chess){
        animationInterval =  setInterval(doAnimate,gameData.animationInfo.eachTime)
    }

}

const doAnimate = () => {

    // if(animationInfo.startX+animationInfo.eachX<animationInfo.endX){
    //     animationInfo.startX+=animationInfo.eachX
    // }
    // if(animationInfo.startY+animationInfo.eachY>animationInfo.endY){
    //     animationInfo.startY+=animationInfo.eachY
    // }
    if(!gameData.animationInfo.chess) {
        clearInterval(animationInterval)
    }
    // console.log('animation', gameData.animationInfo);

    let disX = Math.abs(gameData.animationInfo.endX-gameData.animationInfo.startX)
    let disY = Math.abs(gameData.animationInfo.endY-gameData.animationInfo.startY)

    if(disX>=gameData.animationInfo.eachX_abs){
        gameData.animationInfo.startX+=gameData.animationInfo.eachX
    }
    if(disY>=gameData.animationInfo.eachY_abs){
        gameData.animationInfo.startY+=gameData.animationInfo.eachY
    }

    if(disX<=gameData.animationInfo.eachX_abs
        && disY<=gameData.animationInfo.eachY_abs){
        renderGame()
        gameData.animationInfo.chess=null
        clearInterval(animationInterval)
        renderGame()
    }else {
        renderGame()
    }


}

const countXiang = () => {
    let xiangArr =  getPlayer().chessArr.filter(chess=>chess.name==='相' || chess.name==='象')
    return xiangArr.length
}



// wx.onShow(function(res){
//     requestAnimationFrame(function () {
//         renderGame();
//     });
// });